package org.example;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangjg
 * @desc p
 * @date 2023/03/31 16:32
 **/
public class PTest {

    private static final Logger logger = LoggerFactory.getLogger(PTest.class);

    public static void main(String[] args) {
        String nsrUrl = args[0];
        String topicName = args[1];
        int totalCnt = Integer.parseInt(args[2]);
        int sleepTime = Integer.parseInt(args[3]);

        // 初始化一个producer并设置Producer group name
        DefaultMQProducer producer = new DefaultMQProducer("pg_PTest"); //（1）
        // 设置NameServer地址
        producer.setNamesrvAddr(nsrUrl);  //（2）
        try {
            List<Message> list = new ArrayList<>();
            // 启动producer
            producer.start();
            for (long i = 1; i <= totalCnt; i++) {
//            for (long i = 10001; i <= 50000L; i++) {
//                list.clear();
//                for(int k=1;k<=200;k++) {
//                    // 创建一条消息，并指定topic、tag、body等信息，tag可以理解成标签，对消息进行再归类，RocketMQ可以在消费端对tag进行过滤
//                    Message msg = new Message("t1" /* Topic */,
//                            "Tag_"+k /* Tag */,
//                            ("Hello RocketMQ " + i+"_"+k).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
//                    );   //（3）
//                    msg.setKeys("key_"+k);
//                    msg.putUserProperty("k1", "v1_" + i);
//                    msg.putUserProperty("k2", "v2_" + i);
//                    list.add(msg);
//                }
                // 利用producer进行发送，并同步等待发送结果
                Message msg = new Message(topicName /* Topic */,
                        "Tag_" + i /* Tag */,
                        ("Hello RocketMQ " + i + " queue_" + (i % 8) +" " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_MS_PATTERN)).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
                );   //（3）
                msg.setKeys("key1_" + (i % 8));
                msg.putUserProperty("k1", "v1_" + i);
                msg.putUserProperty("k2", "v2_" + i);

                SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        Long id = (Long) arg;
                        int index = (int) (id % mqs.size());
                        return mqs.get(index);
                    }
                }, i);   //（4）
//                logger.info("--send size={},status={}",list.size(),sendResult.getSendStatus());
//                logger.info("i={},msg={},status={}",i, msg.toString(), sendResult.getSendStatus());
//                TimeUnit.MILLISECONDS.sleep(sleepTime);
                if (sendResult.getSendStatus() != SendStatus.SEND_OK) {
                    logger.error("xxxxxxxxxxx sendfail");
                }
            }

            TimeUnit.SECONDS.sleep(3);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            // 一旦producer不再使用，关闭producer
            producer.shutdown();
        }

    }
}
